//
//  MateInfoViewController.m
//  moon
//
//  Created by beyself on 16/6/18.
//  Copyright © 2016年 beyself. All rights reserved.
//
#import "Utils.h"
#import "MateInfoViewController.h"
#import "UIImageView+AFNetworking.h"
#import "ChatViewController.h"
#import "UserSpaceViewController.h"

@interface MateInfoViewController ()<UITextFieldDelegate>

@end

@implementation MateInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"详细信息";
    
    NSMutableDictionary* param = [[NSMutableDictionary alloc] init];
    [param setValue:APPDELEGATE.mMemberInfo[@"id"] forKey:@"id"];
    [param setValue:_mUserId forKey:@"member_id"];
    [Utils sendHttpPost:param method:@"get_member_info" controller:self flag:0];
    
    UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singleTap:)];
    [singleTapGestureRecognizer setNumberOfTapsRequired:1];
    [self.view addGestureRecognizer:singleTapGestureRecognizer];
}

- (void)singleTap:(UIGestureRecognizer*)gestureRecognizer
{
    UITextField* textfield = (UITextField*)[self.view viewWithTag:1000];
    [textfield resignFirstResponder];
}

- (void) modifyName
{
    UITextField* textfield = (UITextField*)[self.view viewWithTag:1000];
    [textfield resignFirstResponder];
    
    NSMutableDictionary* param = [[NSMutableDictionary alloc] init];
    [param setValue:APPDELEGATE.mMemberInfo[@"id"] forKey:@"id"];
    [param setValue:_mUserId forKey:@"member_id"];
    [param setValue:textfield.text forKey:@"alias"];
    [Utils sendHttpPost:param method:@"set_member_alias" controller:self flag:1];
}

- (void) httpCallback:(NSDictionary*)data flag:(int)flag
{
    if(flag == 0)
    {
        NSDictionary* member = data[@"member"];
        _mUserInfo = [[NSMutableDictionary alloc] initWithDictionary:member];
        [self fillContent];
    }
    else if(flag == 1)
    {
        NSMutableDictionary* param = [[NSMutableDictionary alloc] init];
        [param setValue:APPDELEGATE.mMemberInfo[@"id"] forKey:@"id"];
        [Utils sendHttpPost:param method:@"get_my_group_member_list" controller:self flag:2];
    }
    else if(flag == 2)
    {
        [Utils saveCustomObject:data[@"members"] key:ALL_MEMBER];
        [NSThread detachNewThreadSelector:@selector(refreshMember:) toTarget:self withObject:data[@"members"]];
        [self showAllTextDialog:@"修改成功"];
        
        [APPDELEGATE setTabInit:YES tab:0];
        [APPDELEGATE setTabInit:YES tab:1];
        [APPDELEGATE setTabInit:YES tab:2];
        [APPDELEGATE setTabInit:YES tab:3];
        
        [APPDELEGATE.mMainViewController buttonClick:APPDELEGATE.mMainViewController.mTabBtn];
    }
}

- (void) refreshOnMain:(RCUserInfo*)user
{
    [[RCIM sharedRCIM] refreshUserInfoCache:user withUserId:user.userId];
}

- (void) refreshMember:(NSDictionary*)data
{
    NSDictionary* userInfo = data[_mUserId];
    if (userInfo && userInfo.count) {
        NSString* path = @"";
        if([Utils isStringNullOrEmpty:[userInfo[@"avatar"] description]])
        {
            if([userInfo[@"is_teacher"] intValue] == 1)
            {
                path = @"http://odv1e0gp0.bkt.clouddn.com/ic_teacher.png";
            }
            else
            {
                path = @"http://odv1e0gp0.bkt.clouddn.com/ic_family.png";
            }
        }
        else path = [NSString stringWithFormat:@"%@%@",IMG_URL,userInfo[@"avatar"]];
        
        RCUserInfo *users=[RCUserInfo new];
        users.portraitUri = path;
        users.name = [self getUsername:_mUserId];
        users.userId = _mUserId;
        
        [self performSelectorOnMainThread:@selector(refreshOnMain:) withObject:users waitUntilDone:YES];
    }
}

- (void) fillContent
{
    int yPos = 10;
    UIView* subview = [[UIView alloc] init];
    subview.frame = CGRectMake(10, yPos, 0, 0);
    subview.layer.cornerRadius = 5;
    subview.layer.masksToBounds = YES;
    subview.backgroundColor = WHITE;
    [self.view addSubview:subview];
    
    UIImageView* imageview = [[UIImageView alloc] init];
    imageview.frame = CGRectMake(10, 10, 44, 44);
    imageview.layer.cornerRadius = 22;
    imageview.layer.masksToBounds = YES;
    imageview.contentMode = UIViewContentModeScaleAspectFill;
    if([_mUserInfo[@"is_teacher"] intValue] == 0)
        [imageview setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMG_URL,_mUserInfo[@"avatar_path"]]]
                  placeholderImage:[UIImage imageNamed:@"ic_family"]];
    else
        [imageview setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMG_URL,_mUserInfo[@"avatar_path"]]]
                  placeholderImage:[UIImage imageNamed:@"ic_teacher"]];
    
    [subview addSubview:imageview];
    
    UILabel* label = [[UILabel alloc] init];
    label.frame = CGRectMake(64, 10, 160, 32);
    label.font = FONT_15;
    label.textColor = ORANGE;
    label.text = _mUserInfo[@"username"];
    [subview addSubview:label];
    
    if(![_mUserId isEqualToString:[APPDELEGATE.mMemberInfo[@"id"] description]])
    for(int i = 2; !_needChat && i < 3; i++)
    {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(SCREEN_WIDTH - (3 - i)*32 - 20, 10, 32, 32);
        button.tag = 1002 + i;
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        if(i == 0)
        {
            [button setImage:[UIImage imageNamed:@"ic_call"] forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"ic_call_focus"] forState:UIControlStateHighlighted];
        }
        if(i == 1)
        {
            [button setImage:[UIImage imageNamed:@"icon_mail"] forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"icon_mail_focus"] forState:UIControlStateHighlighted];
        }
        if(i == 2)
        {
            [button setImage:[UIImage imageNamed:@"icon_talk"] forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"icon_talk_focus"] forState:UIControlStateHighlighted];
        }
        /*
        if(i > 0)
        {
            CALayer* layer = [[CALayer alloc] init];
            layer.frame = CGRectMake(0, 7, .5, 18);
            layer.backgroundColor = LINE.CGColor;
            [button.layer addSublayer:layer];
        }
        */
        [subview addSubview:button];
    }
    
    NSMutableString* str = [[NSMutableString alloc] init];
    NSArray* classes = _mUserInfo[@"classes"];
    NSArray* child = _mUserInfo[@"child"];
    for(NSDictionary* dic in classes)
    {
        if(str.length) [str appendString:@"\n"];
        [str appendString:dic[@"school_name"]];
        NSString* className = dic[@"class_alias"];
        if([Utils isStringNullOrEmpty:className]) className = dic[@"class_name"];
        [str appendString:className];
        [str appendString:@"\n"];
        if([dic[@"is_teacher"] intValue] > 0) [str appendString:dic[@"identitylabel"]];
        BOOL isAdd = NO;
        for(NSDictionary* one in child)
        {
            if([[dic[@"id"] description] isEqualToString:[one[@"class_id"] description]])
            {
                if([dic[@"is_teacher"] intValue] > 0 || isAdd) [str appendString:@","];
                [str appendString:one[@"name"]];
                [str appendString:one[@"identity"]];
                isAdd = YES;
            }
        }
    }
    
    label = [[UILabel alloc] init];
    label.font = FONT_13;
    label.text = str;
    label.lineBreakMode = NSLineBreakByCharWrapping;
    label.numberOfLines = 0;
    label.textColor = GRAY;
    int heigt = [label sizeThatFits:CGSizeMake(SCREEN_WIDTH - 100, 640)].height + 8;
    label.frame = CGRectMake(64, 42, SCREEN_WIDTH - 100, heigt);
    [subview addSubview:label];
    
    subview.frame = CGRectMake(10, 10, SCREEN_WIDTH - 20, heigt + 52);

    yPos += heigt + 62;
    
    if(![_mUserId isEqualToString:[APPDELEGATE.mMemberInfo[@"id"] description]])
    {
        subview = [[UIView alloc] init];
        subview.frame = CGRectMake(10, yPos, SCREEN_WIDTH - 20, 48);
        subview.backgroundColor = WHITE;
        subview.layer.cornerRadius = 5;
        subview.layer.masksToBounds = YES;
        [self.view addSubview:subview];
        
        UILabel* lable = [[UILabel alloc] init];
        lable.frame = CGRectMake(10, 0, 40, 48);
        lable.font =FONT_14;
        lable.textColor = BLACK;
        lable.text = @"备注:";
        [subview addSubview:lable];
        
        UITextField* textfield = [[UITextField alloc] init];
        textfield.frame = CGRectMake(50, 0, SCREEN_WIDTH - 80, 48);
        textfield.font = FONT_14;
        textfield.textColor = BLACK;
        textfield.delegate = self;
        textfield.placeholder = @"请输入备注";
        textfield.tag = 1000;
        NSString* className = _mUserInfo[@"alias"];
        if(![Utils isStringNullOrEmpty:className]) textfield.text = className;
        [subview addSubview:textfield];
        yPos += 58;
        
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"修改"
                                                                                  style:UIBarButtonItemStylePlain
                                                                                 target:self
                                                                                 action:@selector(modifyName)];
    }
    
    UIButton* button  = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(10, yPos, SCREEN_WIDTH - 20, 60);
    button.titleLabel.font = FONT_14;
    button.layer.cornerRadius = 5;
    button.layer.masksToBounds = YES;
    button.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [button setTitleColor:BLACK forState:UIControlStateNormal];
    [button setBackgroundImage:[Utils imageFromColor:WHITE] forState:UIControlStateNormal];
    [button setBackgroundImage:[Utils imageFromColor:LINE] forState:UIControlStateHighlighted];
    [button setTitle:@"个人相册" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(showDetail) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    NSString* urlStr = @"";
    NSDictionary* item = _mUserInfo[@"lastestnews"];
    if(![Utils isStringNullOrEmpty:[item description]] && item.count)  urlStr = item[@"attach"];
    
    NSArray* array = [urlStr componentsSeparatedByString:@","];
    for(int i = 0; i < array.count; i++)
    {
        imageview = [[UIImageView alloc] init];
        imageview.frame = CGRectMake(80 + 50*i, 10, 40, 40);
        imageview.layer.masksToBounds = YES;
        imageview.contentMode = UIViewContentModeScaleAspectFill;
        [imageview setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@get_attach?id=%@&width=%d&height=%d",IMG_URL_0,array[i],160,160]]
                  placeholderImage:IMG_DEFAULT];
        [button addSubview:imageview];
    }
    
    UIButton* arrow = [UIButton buttonWithType:UIButtonTypeCustom];
    arrow.frame = CGRectMake(SCREEN_WIDTH - 58, 0, 48, 60);
    [arrow setImage:[UIImage imageNamed:@"ic_arrow"] forState:UIControlStateNormal];
    [button addSubview:arrow];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void) showDetail
{
    UITextField* textfield = (UITextField*)[self.view viewWithTag:1000];
    [textfield resignFirstResponder];
    
    UserSpaceViewController* subview = [[UserSpaceViewController alloc] init];
    subview.hidesBottomBarWhenPushed = YES;
    subview.mUserId = _mUserId;
    [self.navigationController pushViewController:subview animated:YES];
}

- (void) buttonClick:(UIButton*)btn
{
    UITextField* textfield = (UITextField*)[self.view viewWithTag:1000];
    [textfield resignFirstResponder];
    
    NSDictionary* item = _mUserInfo;
    
    if(btn.tag == 1002)
    {
        [self makeCall:item[@"telephone"]];
    }
    else if(btn.tag == 1003)
    {
        [self sendSms:item[@"telephone"]];
    }
    else
    {
        if([_mUserId isEqualToString:[APPDELEGATE.mMemberInfo[@"id"] description]])
        {
            [self showAllTextDialog:@"不能与自己聊天"];
        }
        else
        {
            ChatViewController *chat = [[ChatViewController alloc]init];
            chat.conversationType = ConversationType_PRIVATE;
            chat.targetId = _mUserId;
            [self.navigationController pushViewController:chat animated:YES];
        }
    }
}

- (void) makeCall:(NSString*)tel
{
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",tel];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];
}

- (void) sendSms:(NSString*)tel
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"sms://%@",tel]];
    [[UIApplication sharedApplication] openURL:url];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
